package com.spring.demo.rabbit.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.spring.demo.rabbit.QueueConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/***
 * @title BusinessListener
 * @description: 不需要为该业务队列配置消费者，不然消息在过期之前可能就被消费者消费了！也就没法实现延迟队列的效果了。
 *
 * @author baiji
 * @version 1.0.0
 * @create 2023/9/7 11:15
 **/
@Slf4j
@Component
public class BusinessListener {

    @RabbitListener(queues = QueueConst.DEAD_LETTER_QUEUE)
    public void handlerDeadLetter(Message message, Channel channel) {
        String body = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("收到死信消息: {}", body);
        log.info("死信消息附带的头消息： {}", JSON.toJSONString(message.getMessageProperties().getHeaders()));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
